package lipengfei.botaiframework.security.jwt.validator.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;

import lipengfei.botaiframework.security.jwt.exception.JWTException;
import lipengfei.botaiframework.security.jwt.validator.ValidationResult;
import lipengfei.botaiframework.security.jwt.validator.Validator;
import lipengfei.botaiframework.security.jwt.validator.ValidatorModel;
import lipengfei.botaiframework.security.jwt.validator.eunm.ValidationState;

import java.time.LocalDateTime;
import java.time.ZoneId;

public class NeedRefreshValidator implements Validator<ValidatorModel> {


    public ValidationResult validate(ValidatorModel validatorModel) throws JWTException {

        DecodedJWT decodedJWT = JWT.decode(validatorModel.getToken());
        DecodedJWT refreshDecodedJWT = JWT.decode(validatorModel.getRefreshToken());


        LocalDateTime expiresAt = LocalDateTime.ofInstant(decodedJWT.getExpiresAt().toInstant(), ZoneId.systemDefault());
        LocalDateTime refreshExpiresAt = LocalDateTime.ofInstant(refreshDecodedJWT.getExpiresAt().toInstant(), ZoneId.systemDefault());

        LocalDateTime now = LocalDateTime.now();

        if (now.isAfter(expiresAt) && now.isBefore(refreshExpiresAt))
            return new ValidationResult(false, ValidationState.NEED_REFRESH);
        else
            return null;
    }
}
